package com.learn.dubbo.core.redis.core;

import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisBase {
	
	private static String JEDIS_IP;
    private static int JEDIS_PORT;
    private static String JEDIS_PASSWORD;
    //private static String JEDIS_SLAVE;
 
    private static JedisPool jedisPool;
 
    static {
			Conf conf = new Conf();
			Properties prop = conf.getProp();
			JEDIS_IP = prop.getProperty("redis.address");
	        JEDIS_PORT = Integer.valueOf(prop.getProperty("redis.port"));
	        JEDIS_PASSWORD = prop.getProperty("redis.password");
	        JedisPoolConfig config = new JedisPoolConfig();
	        config.setMaxTotal(8);
	        config.setMaxIdle(8);//20
	        config.setMaxWaitMillis(5000L);
	        config.setTestOnBorrow(true);
	        config.setTestOnReturn(true);
	        config.setTestWhileIdle(true);
	        config.setMinEvictableIdleTimeMillis(60000l);
	        config.setTimeBetweenEvictionRunsMillis(3000l);
	        config.setNumTestsPerEvictionRun(-1);
	        jedisPool = new JedisPool(config, JEDIS_IP, JEDIS_PORT, 60000,JEDIS_PASSWORD);
    }
    
    /**
     * 获取Jedis实例
     * 
     * @return
     */
    public Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    public void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
    
    /**
     * @Title: flushDB 
     * @author 林彬
     * @Description: 清空当前db 
     * @date 2016年12月28日 下午1:54:52 
     * @return String   
     * @throws
     */
    public String flushDB(){
   	 Jedis jedis = getJedis();
   	 String result = jedis.flushDB();
   	 close(jedis);
   	 return result;
    }
    
    /**
     * @Title: flushDB 
     * @author 林彬
     * @Description: 清空所有db 
     * @date 2016年12月28日 下午1:54:52 
     * @return String   
     * @throws
     */
    public String flushAll(){
   	 Jedis jedis = getJedis();
   	 String result = jedis.flushAll();
   	 close(jedis);
   	 return result;
    }

}
